package com.salt.modules.sys.service;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.salt.common.json.AjaxJson;
import com.salt.common.service.CrudService;
import com.salt.common.utils.StringUtils;
import com.salt.core.ocr.OcrTemplate;
import com.salt.core.oss.OssTemplate;
import com.salt.core.qcc.QccTemplate;
import com.salt.core.redis.cache.SaltRedis;
import com.salt.core.service.ServiceException;
import com.salt.modules.sys.entity.Company;
import com.salt.modules.sys.entity.Office;
import com.salt.modules.sys.entity.Role;
import com.salt.modules.sys.entity.User;
import com.salt.modules.sys.mapper.CompanyMapper;
import com.salt.modules.sys.mapper.RoleMapper;
import com.salt.modules.sys.mapper.UserMapper;
import com.salt.modules.sys.utils.UserUtils;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @Description
 * @Author salt
 * @Date 2022/9/13
 * @Version 1.0.1
 */
@Service
@AllArgsConstructor
@Transactional(readOnly = true)
public class CompanyService extends CrudService<CompanyMapper, Company> {

    private final UserMapper userMapper;
    private final QccTemplate qccTemplate;
    private final RoleMapper roleMapper;
    private final OcrTemplate ocrTemplate;
    private final OssTemplate ossTemplate;
    private final SaltRedis saltRedis;
    private final LoginService loginService;
    private final OfficeService officeService;
    //private final BizCardOcrService bizCardOcrService;

    private static final String QCC_CACH_KEY = "salt:qcc:cach:";
    private static final long QCC_CACH_KEY_DEL = 30;  // 过期时间为30分钟

    public AjaxJson findInfo(String name) {
        JSONObject infoObject = qccTemplate.getInfoObject(name);
        String status = qccTemplate.getStatus(infoObject);
        if (!Objects.equals(status, "200"))
            return AjaxJson.error("请输入企业名称等关键词!");
        String resultInfo = qccTemplate.getResultInfo(infoObject);
        Map<String, String> infoMap = qccTemplate.getInfoMap(infoObject);

        String key = QCC_CACH_KEY + infoMap.get("creditCode");
        if (saltRedis.exists(key))
            saltRedis.del(key);
        saltRedis.set(key, infoMap, Duration.ofMinutes(QCC_CACH_KEY_DEL));
        return AjaxJson.success().put("info", resultInfo);
    }

    public String search() {
        return qccTemplate.search();
    }

    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public AjaxJson upgradeAccount(Company company) {

        // 校验公司名称、营业执照信息、社会信用代码是否正确
        if (StringUtils.isBlank(company.getCreditCode()))
            return AjaxJson.error("企业社会统一信用代码不能为空!");
        if (StringUtils.isBlank(company.getName()))
            return AjaxJson.error("企业名称不能为空!");
        if (StringUtils.isBlank(company.getAuthMaterial()))
            return AjaxJson.error("上传的营业执照不能为空!");

        // 一个企业只能注册一个账号
        if (mapper.countByCreditCode(company.getCreditCode()) > 0)
            return AjaxJson.error("一个公司只能升级一个账号");

        Map<String, String> infoMap = saltRedis.get(QCC_CACH_KEY + company.getCreditCode());
        if (infoMap == null || infoMap.isEmpty())
            return AjaxJson.error("填报的信息已失效，请重新填报!");
        company.setName(infoMap.get("name"));
        company.setProvince(infoMap.get("province"));
        company.setCity(infoMap.get("city"));
        company.setCounty(infoMap.get("county"));
        saltRedis.del(QCC_CACH_KEY + company.getCreditCode());

        // 验证营业执照
        String[] split = company.getAuthMaterial().split("/", 5);

        /*BizLicenseInfo bizLicenseInfo = bizCardOcrService.getBizLicenseInfo(ossTemplate.getObject(split[4]));
        System.out.println(bizLicenseInfo.getName());
        System.out.println(bizLicenseInfo.getCreditCode());
        System.out.println(bizLicenseInfo.getAddress());*/


        /*String doc = ocrTemplate.doOcr(ossTemplate.getObject(split[4]));
        System.out.println("doc: " + doc);
        if (!doc.contains(company.getName()) || !doc.contains(company.getCreditCode()))
            return AjaxJson.error("上传的该企业的营业执照有误!");*/

        company.setAuthMaterial(split[4]);

        // 将公司信息添加到组织机构中
        Office office = new Office();
        office.setName(company.getName());
        office.setType("1");
        office.setGrade("1");
        office.setUseable("1");
        office.setSort(30);
        office.setFuncLocation("1");
        officeService.save(office);

        company.setCompanyOfficeId(office.getId());
        super.save(company);

        User user = UserUtils.getUser();
        userMapper.updateCompanyById(company.getId(), office.getId(), user.getId());
        String systemType = loginService.getCachLoginSystemType(user.getId());

        List<Role> roleList = getRoleList(company.getType(), systemType);
        if (roleList.size() > 0){
            user.setRoleList(roleList);
            userMapper.deleteUserRole(user);
            userMapper.insertUserRole(user);
            // 清除用户缓存
            UserUtils.clearCache(user);
            UserUtils.clearUserDataCache();
            UserUtils.get(user.getId());
            UserUtils.getOfficeList();
            UserUtils.getRoleList();
            UserUtils.getOfficeAllList();
        } else {
            throw new ServiceException(user.getLoginName() + "没有设置角色！");
        }
        return AjaxJson.success("账号升级成功!");
    }

    public Company getCompanyInfo() {
        Company company = UserUtils.getUser().getCompany1();
        if (company != null && StringUtils.isNotBlank(company.getId())) {
            company = mapper.get(company.getId());
            company.setAuthMaterial(ossTemplate.outerFileLink(company.getAuthMaterial()));
        } else {
            company = new Company();
        }
        return company;
    }

    public Company findByCompanyOfficeId(String companyOfficeId){
        return mapper.findByCompanyOfficeId(companyOfficeId);
    }

    private List<Role> getRoleList(String companyType, String systemType) {
        List<Role> roleList = Lists.newArrayList(); // 升级后默认拥有的角色
        roleList.add(roleMapper.get("0"));
        if (Objects.equals("1", systemType)) {  //
            if (Objects.equals(companyType, "1")) {  // 企业
                roleList.add(roleMapper.get("4"));
            } else if (Objects.equals(companyType, "2")) {  // 机构
                roleList.add(roleMapper.get("5"));
            } else if (Objects.equals(companyType, "3")) {  // 政府
                roleList.add(roleMapper.get("6"));
            }
        } else if (Objects.equals("2", systemType)) {  //
            if (Objects.equals(companyType, "1")) {  // 企业
                roleList.add(roleMapper.get("1"));
            } else if (Objects.equals(companyType, "2")) {  // 机构
                roleList.add(roleMapper.get("2"));
            } else if (Objects.equals(companyType, "3")) {  // 政府
                roleList.add(roleMapper.get("3"));
            }
        }
        return roleList;
    }
}
